#coding:utf-8


PHOTOPATH = 'photo'
from twisted.internet import defer
import os
import buss 
import dttime
import datamethod as dm
import protocols
from protocols import Protocol4101,Protocol4110,Protocol4141,Protocol4150

def writeDataToFile(filename, data):
    if not os.path.exists(PHOTOPATH): 
        os.mkdir(PHOTOPATH)
    f = file("%s/%s"%(PHOTOPATH, filename), 'wb')
    for d in data:
        f.write(d)
    f.close()
    
class Hunter(buss.HunterMaster):
    def init(self):
        self.imageData = {}
        self.curIndex = None
        self.curTotals = None
    
    def p_4101(self, data):
        p = Protocol4101(data)
        self.photoNumbers = (p.getCamera1() + p.getCamera2() + p.getCamera3()
                             + p.getCamera4()) * p.getNumbers()
        self.sendData(p)
        
    def p_4141(self, data):
        p = Protocol4110(data)
        if not p.getResponse():
            self.endWork()
        
    def savePhoto(self):
        filename = "%s-%s.jpg"%(self.work.tel, dttime.series())
        data = []
        for i in range(self.curTotals):
            data.append(dm.data2hex(self.imageData.get(i, [])))
        defer.succeed(filename).addCallback(writeDataToFile, data)
        self.init()
        self.photoNumbers -= 1
        if self.photoNumbers <= 0:
            self.nextTest()
    
    def p_4150(self, data):
        p = Protocol4150(data)
        self.curIndex = p.getImageIndex()
        self.curTotals = p.getPackageSum()
        curPackage = p.getPackageNumber()
        self.imageData[curPackage] = p.getImageData()
        if (curPackage + 1) % 0x10 == 0 or \
            curPackage == self.curTotals - 1:
            self.replyImageTransport(curPackage)
            
    def replyImageTransport(self, curPackage):
        lack = []
        for number in range(curPackage):
            if not self.imageData.has_key(number):
                lack.append(number)
        data = Protocol4110()
        data.setImageIndex(self.curIndex)
        data.setPackageNumber(curPackage)
        data.setLackPackage(lack)
        self.sendData(data)
        if curPackage == self.curTotals - 1 and lack == []:
            #self.savePhoto()
            self.photoNumbers -= 1
            if self.photoNumbers <= 0:
                self.endWork()
            